package com.example.yls.cnbetaapp.httpService;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.yls.cnbetaapp.activity.ContentActivity;
import com.example.yls.cnbetaapp.amqp.RPCClient;
import com.example.yls.cnbetaapp.component.OnTvGlogbalLayoutListener;
import com.example.yls.cnbetaapp.entity.ArticleEntity;
import com.example.yls.cnbetaapp.util.GetBitmapUtil;
import com.example.yls.cnbetaapp.util.HttpUrlConnectionUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArticleService {
    public void sendArticleToMessageQue(Handler handler, int mid){
        ArticleEntity articleEntity = new ArticleEntity();
//        String articleUrl = "http://192.168.0.13:8080/getArticleJson?mid="+mid;
//        HttpUrlConnectionUtil httpUtil = new HttpUrlConnectionUtil();
//        String articleJson = httpUtil.getObjJson(articleUrl);
        RPCClient rpcClient = new RPCClient();
        String articleJson = rpcClient.getServerContent("article","articleQueue","articleExchange","articleReply",String.valueOf(mid));
        try {
            JSONObject jsonObject = new JSONObject(articleJson);
            articleEntity.setArticle_title(jsonObject.getString("article_title"));
            articleEntity.setArticle_summary(jsonObject.getString("article_summary"));
            articleEntity.setSummary_imgUrl(jsonObject.getString("summary_imgUrl"));
            articleEntity.setArticle_content(jsonObject.getString("article_content"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = articleEntity;
        handler.sendMessage(msg);
    }

    public void setSummaryImg(final ImageView view, final ArticleEntity articleEntity){
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                Bitmap bitmap =(Bitmap) msg.obj;
                view.setImageBitmap(bitmap);
            }
        };
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = GetBitmapUtil.getBitmap(articleEntity.getSummary_imgUrl());
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = bitmap;
                handler.sendMessage(msg);
            }
        });
        thread.start();
    }

    /**
     * 设置文章图片
     * @param view
     * @param imgUrl
     */
    public void setContentImg(final ImageView view, final String imgUrl){
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                Bitmap bitmap =(Bitmap) msg.obj;
                view.setImageBitmap(bitmap);
            }
        };
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = GetBitmapUtil.getBitmap(imgUrl);
                Message msg = Message.obtain();
                msg.what = 2;
                msg.obj = bitmap;
                handler.sendMessage(msg);
            }
        });
        thread.start();
    }
    /**
     *显示文章内容
      * @param mcontext
     * @param linearLayout
     * @param articleEntity
     */
    public void setArticleContent(Context mcontext, final LinearLayout linearLayout, final ArticleEntity articleEntity){
        //1.先将文章分段，以图片链接点为分界点截成数组
        String article_content = articleEntity.getArticle_content();
        String[] articleArray = splitImgUrl(article_content);
        //2.图片链接点之前之后都用textView控件显示文字，动态添加textView控件。
        for(String article:articleArray){
            if(!"".equals(article) && article != null){
                if(article.contains(".jpg") || article.contains(".png")) {
                    ImageView img = new ImageView(mcontext);
                    setContentImg(img,article);
                    LinearLayout.LayoutParams relativeLayout_parent_params
                            = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                    linearLayout.addView(img,relativeLayout_parent_params);
                }else {
                    TextView tx = new TextView(mcontext);
                    tx.setText("\u3000\u3000"+article);
                    tx.setPadding(10,10,10,0);
                    tx.getViewTreeObserver().addOnGlobalLayoutListener(new OnTvGlogbalLayoutListener(tx));
                    LinearLayout.LayoutParams relativeLayout_parent_params
                            = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                    linearLayout.addView(tx);
                }
            }
        }
    }

    public String[] splitImgUrl(String article_content){
      String reg = "http.*?(jpg|png)";
      String[] articleArray = new String[30];
      String[] httpArray = new String[20];
      Pattern pattern = Pattern.compile(reg);
      Matcher matcher = pattern.matcher(article_content);
      int count = 0;
        for(int i = 0;matcher.find();i++) {
            httpArray[i] = matcher.group();
            count++;
        }
      String newArticle = matcher.replaceAll("￥");
      int currenttIndex = 0;
      int befforeIndex = 0;
      for(int i = 0,j = 0;(currenttIndex = newArticle.indexOf("￥",currenttIndex)) != -1;i++,j++) {
          if(count == 1) {
              articleArray[i] = newArticle.substring(0, currenttIndex);
              articleArray[i+1] = httpArray[j];
              articleArray[i+2] = newArticle.substring(currenttIndex+1);
              return articleArray;
          }else {
              if (i == 0) {
                  articleArray[i] = newArticle.substring(0, currenttIndex);
                  articleArray[i + 1] = httpArray[j];
              } else if(j == count){
                  articleArray[i+1] = newArticle.substring(befforeIndex);
              }else {
                  if(befforeIndex >= currenttIndex){
                      articleArray[i] = httpArray[j];
                  }else {
                      articleArray[i] = newArticle.substring(befforeIndex,currenttIndex);
                      articleArray[i+1] = httpArray[j];
                  }

              }
          }
          currenttIndex = currenttIndex+1;
          befforeIndex = currenttIndex;
          i++;
      }
      if(count == 0){
          articleArray[0] = article_content;
      }
      return articleArray;
    }
}
